Coverage for tests/test_templates.py: 10%

180 statements  

« prev     ^ index     » next       coverage.py v7.4.1, created at 2024-02-01 11:20 +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 = {"instrument": "dummy", "visit": 52, "physical_filter": "Most Amazing U Filter Ever"} 

85 

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

87 fileTmpl = FileTemplate(template) 

88 path = fileTmpl.format(ref) 

89 self.assertEqual(path, answer) 

90 

91 def testBasic(self): 

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

93 self.assertTemplate( 

94 tmplstr, 

95 "run2/calexp/00052/Most_Amazing_U_Filter_Ever", 

96 self.makeDatasetRef("calexp"), 

97 ) 

98 tmplstr = "{run}/{datasetType}/{visit:05d}/{physical_filter}-trail" 

99 self.assertTemplate( 

100 tmplstr, 

101 "run2/calexp/00052/Most_Amazing_U_Filter_Ever-trail", 

102 self.makeDatasetRef("calexp"), 

103 ) 

104 

105 tmplstr = "{run}/{datasetType}/{visit:05d}/{physical_filter}-trail-{run}" 

106 self.assertTemplate( 

107 tmplstr, 

108 "run2/calexp/00052/Most_Amazing_U_Filter_Ever-trail-run2", 

109 self.makeDatasetRef("calexp"), 

110 ) 

111 self.assertTemplate( 

112 tmplstr, 

113 "run_2/calexp/00052/Most_Amazing_U_Filter_Ever-trail-run_2", 

114 self.makeDatasetRef("calexp", run="run/2"), 

115 ) 

116 

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

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

119 

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

121 

122 self.assertTemplate( 

123 "fixed/{id}", 

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

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

126 ) 

127 

128 self.assertTemplate( 

129 "fixed/{id}_{physical_filter}", 

130 f"fixed/{str(REFUUID)}_Most_Amazing_U_Filter_Ever", 

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

132 ) 

133 

134 # Retain any "/" in run 

135 tmplstr = "{run:/}/{datasetType}/{visit:05d}/{physical_filter}-trail-{run}" 

136 self.assertTemplate( 

137 tmplstr, 

138 "run/2/calexp/00052/Most_Amazing_U_Filter_Ever-trail-run_2", 

139 self.makeDatasetRef("calexp", run="run/2"), 

140 ) 

141 

142 # Check that "." are replaced in the file basename, but not directory. 

143 dataId = {"instrument": "dummy", "visit": 52, "physical_filter": "g.10"} 

144 self.assertTemplate( 

145 tmplstr, 

146 "run.2/calexp/00052/g_10-trail-run_2", 

147 self.makeDatasetRef("calexp", run="run.2", dataId=dataId), 

148 ) 

149 

150 with self.assertRaises(FileTemplateValidationError): 

151 FileTemplate("no fields at all") 

152 

153 with self.assertRaises(FileTemplateValidationError): 

154 FileTemplate("{visit}") 

155 

156 with self.assertRaises(FileTemplateValidationError): 

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

158 

159 with self.assertRaises(FileTemplateValidationError): 

160 FileTemplate("{id}/fixed") 

161 

162 with self.assertRaises(FileTemplateValidationError): 

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

164 

165 def testRunOrCollectionNeeded(self): 

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

167 with self.assertRaises(FileTemplateValidationError): 

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

169 

170 def testNoRecord(self): 

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

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

173 # does fail. 

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

175 with self.assertRaises(RuntimeError) as cm: 

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

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

178 

179 def testOptional(self): 

180 """Optional units in templates.""" 

181 ref = self.makeDatasetRef("calexp") 

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

183 self.assertTemplate( 

184 tmplstr, 

185 "run2/calexp/v00052_fMost_Amazing_U_Filter_Ever", 

186 self.makeDatasetRef("calexp"), 

187 ) 

188 

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

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

191 

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

193 # is optional 

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

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

196 

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

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

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

200 

201 # Optionals with some text between fields 

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

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

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

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

206 

207 def testComponent(self): 

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

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

210 refMetric = self.makeDatasetRef("metric") 

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

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

213 

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

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

216 

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

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

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

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

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

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

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

224 

225 # Providing a component but not using it 

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

227 with self.assertRaises(KeyError): 

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

229 

230 def testFields(self): 

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

232 # special fields, optional special fields 

233 testData = ( 

234 ( 

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

236 {"visit", "physical_filter"}, 

237 set(), 

238 {"run", "datasetType"}, 

239 set(), 

240 ), 

241 ( 

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

243 {"visit"}, 

244 set(), 

245 {"run"}, 

246 {"component"}, 

247 ), 

248 ( 

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

250 {"physical_filter", "instrument"}, 

251 {"visit"}, 

252 {"run", "datasetType"}, 

253 {"component"}, 

254 ), 

255 ) 

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

257 with self.subTest(template=tmplstr): 

258 tmpl = FileTemplate(tmplstr) 

259 fields = tmpl.fields() 

260 self.assertEqual(fields, mandatory) 

261 fields = tmpl.fields(optionals=True) 

262 self.assertEqual(fields, mandatory | optional) 

263 fields = tmpl.fields(specials=True) 

264 self.assertEqual(fields, mandatory | special) 

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

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

267 

268 def testSimpleConfig(self): 

269 """Test reading from config file""" 

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

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

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

273 ref = self.makeDatasetRef("calexp") 

274 tmpl = templates.getTemplate(ref) 

275 self.assertIsInstance(tmpl, FileTemplate) 

276 

277 # This config file should not allow defaulting 

278 ref2 = self.makeDatasetRef("unknown") 

279 with self.assertRaises(KeyError): 

280 templates.getTemplate(ref2) 

281 

282 # This should fall through the datasetTypeName check and use 

283 # StorageClass instead 

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

285 tmplSc = templates.getTemplate(ref3) 

286 self.assertIsInstance(tmplSc, FileTemplate) 

287 

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

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

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

291 tmplCalexp = templates.getTemplate(ref) 

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

293 tmpl_image = templates.getTemplate(refImage) 

294 self.assertIsInstance(tmplCalexp, FileTemplate) 

295 self.assertIsInstance(tmpl_image, FileTemplate) 

296 self.assertIsInstance(tmplWcs, FileTemplate) 

297 self.assertEqual(tmplCalexp, tmpl_image) 

298 self.assertNotEqual(tmplCalexp, tmplWcs) 

299 

300 # Check dimensions lookup order. 

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

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

303 # It should match dimensions 

304 refDims = self.makeDatasetRef( 

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

306 ) 

307 tmplDims = templates.getTemplate(refDims) 

308 self.assertIsInstance(tmplDims, FileTemplate) 

309 self.assertNotEqual(tmplDims, tmplSc) 

310 

311 # Test that instrument overrides retrieve specialist templates 

312 refPvi = self.makeDatasetRef("pvi") 

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

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

315 

316 tmplPvi = templates.getTemplate(refPvi) 

317 tmplPviHsc = templates.getTemplate(refPviHsc) 

318 tmplPviLsst = templates.getTemplate(refPviLsst) 

319 self.assertEqual(tmplPvi, tmplPviLsst) 

320 self.assertNotEqual(tmplPvi, tmplPviHsc) 

321 

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

323 refNoPviHsc = self.makeDatasetRef( 

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

325 ) 

326 tmplNoPviHsc = templates.getTemplate(refNoPviHsc) 

327 self.assertNotEqual(tmplNoPviHsc, tmplDims) 

328 self.assertNotEqual(tmplNoPviHsc, tmplPviHsc) 

329 

330 # Format config file with defaulting 

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

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

333 tmpl = templates.getTemplate(ref2) 

334 self.assertIsInstance(tmpl, FileTemplate) 

335 

336 # Format config file with bad format string 

337 with self.assertRaises(FileTemplateValidationError): 

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

339 

340 # Config file with no defaulting mentioned 

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

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

343 with self.assertRaises(KeyError): 

344 templates.getTemplate(ref2) 

345 

346 # Try again but specify a default in the constructor 

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

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

349 tmpl = templates.getTemplate(ref2) 

350 self.assertEqual(tmpl.template, default) 

351 

352 def testValidation(self): 

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

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

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

356 

357 entities = {} 

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

359 "calexp", 

360 storageClassName="StorageClassX", 

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

362 ) 

363 

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

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

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

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

368 

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

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

371 ) 

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

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

374 ) 

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

376 "calexp.wcs", 

377 storageClassName="StorageClassX", 

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

379 conform=False, 

380 ) 

381 

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

383 "filter_inst", 

384 storageClassName="StorageClassX", 

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

386 ) 

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

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

389 ) 

390 

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

392 "filter_inst", 

393 storageClassName="StorageClassX", 

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

395 ) 

396 

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

398 "filter_inst", 

399 storageClassName="Integer", 

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

401 ) 

402 

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

404 

405 # Rerun but with a failure 

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

407 with self.assertRaises(FileTemplateValidationError): 

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

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

410 

411 

412if __name__ == "__main__": 

413 unittest.main()